package com.swak.redis.mock;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

import com.swak.test.utils.Scanners;
import com.swak.utils.buffer.ByteBuffers;

public class RedisClient {

	private SocketChannel client;
	private ByteBuffer buffer;

	public RedisClient() throws UnknownHostException, IOException {
		this.client = SocketChannel.open(new InetSocketAddress("192.168.137.140", 7002));
		this.client.configureBlocking(true);
		this.buffer = ByteBuffer.allocate(1024);
	}

	public void exec(String command) {
		String cmd = command + "\n";
		this.buffer.clear();
		this.buffer.put(cmd.getBytes());
		this.buffer.flip();
		try {
			this.client.write(this.buffer);
			System.out.println("发送命令：" + command);
			this.buffer.flip();
			this.client.read(this.buffer);
			this.buffer.flip();
			String result = new String(ByteBuffers.getBytes(this.buffer, 0, this.buffer.limit()));
			System.out.println("读取数据:" + result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws UnknownHostException, IOException {
		RedisClient client = new RedisClient();
		Scanners.scan((command) -> {
			client.exec(command);
		});
	}
}
